<template>
  <div id="w-colorBar" @click="handleClick" class="slider-bar w-sloder-color">
    <div id="w-barpicker" :style="{ left: sliderLeft + 'px' }" class="slider-bar-pointer bg-color"></div>
  </div>
</template>

<script>
export default {
  name: 'w-slider-color',
  props: {
    color: {
      required: true
    },
    sliderType:{
      type:String,
      default:'color'
    }
  },
  data() {
    return {
      isDragging: false,
      sliderLeft: 0,
    }
  },
  computed: {
    //获取色相值
    hueValue() {
      const hue = this.color.get('hue');
      return hue;
    }
  },

  watch: {
    hueValue(val) {
      console.log('监听色相变化',val)
      this.updateView();
    }
  },

  mounted() {
    let that = this;
    let rightBar = document.querySelector('#w-colorBar');
    this.updateView();
    rightBar.addEventListener('mousedown', e => {
      if (that.isDragging) return; //防止重复
      console.log("按下")
      document.onselectstart = () => false;
      document.ondragstart = () => false;
      document.addEventListener('mousemove', that.moveFn);
      document.addEventListener('mouseup', that.upFn);
      that.isDragging = true;
    })
  },
  methods: {
    //点击时
    handleClick(event) {
      const thumb = document.querySelector('#w-barpicker');
      const target = event.target;
      if (target !== thumb) {
        this.moveFn(event);
      }
    },

    moveFn(event) {
      //滑轨位置信息
      let sliderBar = document.querySelector('#w-colorBar').getBoundingClientRect();
      let slider = document.querySelector('#w-barpicker');

      //滑块滑动的范围
      let left = event.clientX - sliderBar.left;
      left = Math.min(left, sliderBar.width - slider.offsetWidth / 2);
      left = Math.max(slider.offsetWidth / 2, left);//
      //将滑块滑动的范围转换成色相 （滑块滑动的距离/滑块的范围高度）*360
      let hue = Math.round((left - slider.offsetWidth / 2) / (sliderBar.width - slider.offsetWidth) * 360);
      //记录色相
      this.color.set('hue', hue);

    },
    upFn(event) {
      console.log('松开')
      document.removeEventListener('mousemove', this.moveFn);
      document.removeEventListener('mouseup', this.upFn);
      document.onselectstart = null;
      document.ondragstart = null;
      this.isDragging = false;
    },
    //根据色想变化更新位置
    updateView(){
      //由const hue=（滑块滑动的距离/滑块的范围高度）*360  得到 滑块滑动的距离=hue/360*滑块的范围高度
      let sliderBar = document.querySelector('#w-colorBar').getBoundingClientRect();
      let slider = document.querySelector('#w-barpicker');
      const hue = this.color.get('hue');
      this.sliderLeft= Math.round((hue/360)*(sliderBar.width-slider.offsetWidth));
      console.log("移动距离", this.sliderLeft)

    }
  },
}
</script>

<style scoped>
@import './commom.css';
.w-sloder-color {
  background: linear-gradient(to right, #f00 , #ff0, #0f0, #0ff, #00f, #f0f, #f00);
}
.bg-color{
  background: #ffffff;
}
</style>
